<template>
	<view>
		<form @submit="formSubmit">
			<view class="cu-form-group bottom">
				<textarea  name="content"  placeholder="输入要分享的内容" v-model="post.content"></textarea>
			</view>
			<view class="cu-form-group">
				<view class="action">
					分享图片上传
				</view>
				<view class="action">
					{{imgList.length}}/10
				</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img margin-top" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
					 <image :src="imgList[index]" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
							<text class='cuIcon-close' name="photo"></text>
						</view>
					</view>
					<view class="solids margin-top" @tap="ChooseImage" v-if="imgList.length<10">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
			<view class="padding flex flex-direction">
				<button class="cu-btn block bg-green margin-tb-sm lg" 
				:disabled=btn_disabled :type=btn_type :loading=btn_loading formType="submit">发布</button>
			</view>
		</form>
	</view>
</template>

<script>
	var graceChecker = require("../../plugin/graceUI/jsTools/graceChecker.js");
	export default {
		data() {
			return {
				btn_disabled:false,
				btn_type:'',
				btn_loading:false,
				index: -1,
				imgList: [], //上传的图片
				post: {
					userid: '',
					content: '',
					picturesUrl: '', //上传后的相对路径
				},
				imgList: [], //转换后的图像地址
				tempImgSrc: '', //当前要操作的图片路径，上传或者删除
				imgindex : 0,
				getPostInfoUrl:this.$config.apiUrl+"/dasPostController/",
			};
		},
		onLoad: function(option) {
			let param=this.$Route.query;
			var arr = Object.keys(param);
			if(arr.length != 0){
				this.post=param;
				this.imgList=param.pics;
				this.tempImgSrc=param.picturesUrl.length>0?param.picturesUrl[0]:'';
				// this.getPostInfo();
				// console.log(this.imgList);
				// console.log(this.post);
				
			}
			
		},
		created() {

		},
		methods: {
			/**
			 * 获取详情
			 */
			getPostInfo() {
				if(this.post.id){
					let param={
					};
					this.$http.get(this.getPostInfoUrl+this.post.id,param).then(res=>{
						// console.log(res)
						if (res.data.ok){
							//转换部分值
							this.post=res.data.data;
							let photoUrl=[];
							photoUrl=(this.post.picturesUrl==null || this.post.picturesUrl=="")?'':this.post.picturesUrl.split(",");
							for(var i=0;i<photoUrl.length;i++){
								if(photoUrl[i]!='' && photoUrl[i]!=null){
									var imgURL=this.$config.imgUrl+'/'+photoUrl[i];
									this.imgList.push(imgURL);
									this.tempImgSrc=photoUrl[i];
								}
							}
						}
					}).catch(()=>{
						this.$tip.error('获取分享失败！')
					});
				}
			},
			ChooseImage() {
				uni.chooseImage({
					count: 10, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths)
						} else {
							this.imgList = res.tempFilePaths
						}
						// for(let i=this.imgindex;i<this.imgList.length;i++,this.imgindex++){
						// 	this.tempImgSrc = this.imgList[i];
						// 	this.dealFile(1, 0, '');
						// }
						 this.tempImgSrc=res.tempFilePaths[0];
						 this.dealFile(1,0,'');
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '删除照片',
					content: '确定要删除吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							if(this.post.id){
								let lj=this.imgList[e.currentTarget.dataset.index];
								let index=lj.indexOf("server");
								this.tempImgSrc=lj.substring(index+7,lj.length);
								this.dealFile(0,1,this.tempImgSrc);
							}
							// console.log("delPath",this.tempImgSrc);
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			//处理附件
			dealFile(isup,isdel,delPath){
				uni.uploadFile({
				    url: this.$config.apiUrl+"/appUploadController/dealFile",
					filePath: this.tempImgSrc,//当前要操作的图片路径，上传或者删除
					fileType: 'image',
					name: 'file',//后端通过'file'获取上传的文件对象
				    formData: {
						isup:isup,
						isdel:isdel,
						bizType:'photosucai',
						delPath:delPath
					},
				    success: (res) => {
						// console.log(res)
				        if (res.statusCode === 200) {
							let data=JSON.parse(res.data);
							let msg=data.message;
							if(isup==1){
								if(this.post.picturesUrl){
									this.post.picturesUrl+=','+data.data;
								}else{
									this.post.picturesUrl=data.data;
								}
							}else{
								//删除照片及逗号，三次匹配
								this.post.picturesUrl=this.post.picturesUrl.replace(','+delPath,'');
								this.post.picturesUrl=this.post.picturesUrl.replace(delPath+',','');
								this.post.picturesUrl=this.post.picturesUrl.replace(delPath,'');
							}
							// console.log(this.post.photo);
				            uni.showToast({
				                title: msg,
								duration: 2000
				            });
							this.tempImgSrc="";
				        }
				    },
				    fail: (res) => {
				        console.log(res)
				    }
				});
			},
			// 表单提交及验证
			formSubmit : function(e){
				//定义表单规则
				var rule = [
					{name:"content", checkType : "notnull", checkRule:"", errorMsg:"分享内容不能为空!"}
				];
				//进行表单检查 e.detail.value 内存放着表单数据
				let formData = e.detail.value;
				
				formData.id=this.post.id;
				// formData.userid=this.$store.getters.userid;
				formData.picturesUrl=this.post.picturesUrl;
				// console.log(formData);
				var checkRes = graceChecker.check(formData, rule);
				if(checkRes){
					this.btn_loading=true;
					this.btn_disabled=true;
					uni.request({
						url: this.$config.apiUrl+"/dasPostController/savePost",
						method: 'POST',
						header: {
							'content-type': 'application/x-www-form-urlencoded'//这样设置request才能接值
						},
						data:formData,
						success: (res) => {
							//console.log(res);
							if(res.data.ok){
								uni.showToast({
									title: res.data.message,
									duration: 2000
								});
								setTimeout(() => {
									//派发刷新事件，让list刷新数据
									uni.$emit('reloadMyNssq', {msg:'刷新'});
									uni.redirectTo({
										url: './my_nssq_list'
									});
								}, 1000)
							}else{
								uni.showToast({
									title: res.data.message,
									duration: 2000,
									icon: "none"
								});
								this.btn_loading=false;
								this.btn_disabled=false;
							}
							
						},
						fail: (res) => {
							 console.log(res);
						},
						complete: () => {}
					});
				}else{
					uni.showToast({ title: graceChecker.error, icon: "none" });
				}
			}
		}
	}
</script>

<style>
	.bottom {
		border-bottom: 2rpx solid rgb(241, 241, 241);
	}
</style>
